package com.hcy.app.utils

import android.content.ContentUris
import android.content.Context
import android.provider.MediaStore
import androidx.core.database.getStringOrNull
import java.io.File


object FileUtils{

    // 将文件保存到私有存储空间中
    fun saveToPrivateExternal(ctx:Context,orgFile: File,encryption: Boolean=false){
        val externalDir = ctx.getExternalFilesDir("miao")
        val outputFile = File(externalDir, "encrypted_${orgFile.name}")
        if ( encryption ){
//            CryptoUtils.encryptFile(originalFile, outputFile) // todo 需自行实现加密
        }else{
            orgFile.copyTo(outputFile)
        }
        orgFile.delete() // 删除原始文件
    }

    // 获取私有存储空间中的文件
    fun getPrivateExternal(ctx:Context,fileTypes: Set<String>): List<File>{
        val list = mutableListOf<File>()
        // /storage/emulated/0/Android/data/com.hcy.app/files
        val externalDir = ctx.getExternalFilesDir("miao")
        fun walkDir(dir: File?){
            dir?.listFiles()?.forEach { file ->
                if (file.isDirectory){
                    walkDir(file)
                }else{
                    if ( fileTypes.any { file.name.endsWith(it,ignoreCase = true) } ){
                        list.add(file)
                    }
                }
            }
        }
        walkDir(externalDir)
        return list
    }

    // 获取公共空间下的特定文件
    fun getPublicFiles(ctx:Context,fileTypes: Set<String>): List<File>{
        val list = mutableListOf<File>()
        // todo
        return list
    }

    // 基于 MediaStore 获取视频数据
    fun getVideoInfo(ctx:Context): List<File>{
        val videoList = mutableListOf<File>()

        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.SIZE,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.DATA // 文件路径（Android 10+ 可能返回null）
        )

        ctx.contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            projection,
            null,
            null,
            null // 按添加时间倒序
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
                val name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME))
                val size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE))
                val duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION))
                val path = cursor.getStringOrNull(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))

                val uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
                videoList.add(File(path.toString()))
            }
        }
        return videoList
    }







}

